<template>
  <el-dialog :close-on-click-modal="false" :key="dialogShow" v-model="dialogShow" :title="title" top="3vh" :width="700"
    @close="close">
    <div class="flex-y-c">
      <div class="step_box">
        <el-steps style="max-width: 100%" :active="stepActive" align-center>
          <el-step title="产品基础信息" :description="isEdit ? '编辑产品' : '创建产品'" />
          <el-step title="输入产品附件信息" description="输入详细的内容" />
        </el-steps>
      </div>
      <div class="step_content">
        <div class="content_box" v-show="stepActive == 1">
          <el-form ref="formStep" :model="formData" label-width="120" :rules="rules">
            <template v-for="item in propsDialog.step1" :key="item.prop">
              <!-- 做一个判断哦   -->
              <template v-if="item.prop == 'schemeCode'">
                <el-form-item :label="item.label" :prop="item.prop" v-if="formData.productType!=1">
                  <el-select v-model="formData[item.prop]" :placeholder="item.placeholder"
                   :filterable="item.filterable ?? false" style="width: 100%">
                    <el-option v-for="target in item.options" :key="target.key" style="width: 100%"
                      :label="target.value" :value="target.key"></el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item :label="item.label"  v-else>
                  <el-select v-model="formData[item.prop]" :placeholder="item.placeholder"
                   :filterable="item.filterable ?? false" style="width: 100%">
                    <el-option v-for="target in item.options" :key="target.key" style="width: 100%"
                      :label="target.value" :value="target.key"></el-option>
                  </el-select>
                </el-form-item> -->
              </template>
              <el-form-item :label="item.label" :prop="item.prop" v-else>
                <template v-if="item.type == 'select'" style="width: 100%">
                  <el-select v-model="formData[item.prop]" :placeholder="item.placeholder"
                    @change="filterName($event, item.prop)" :filterable="item.filterable ?? false" style="width: 100%">
                    <el-option v-for="target in item.options" :key="target.key" style="width: 100%"
                      :label="target.value" :value="target.key"></el-option>
                  </el-select>
                </template>
                <template v-else-if="item.type == 'custom'">
                  <!-- <slot :name="item.slotName"></slot> -->
                  <template v-for="domain in formData.supplierExtInfo">
                    <el-row style="width: 100%" justify="space-around">
                      <el-col :span="6">
                        <el-input v-model="domain.key" placeholder="请输入value" :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea"></el-input>
                      </el-col>
                      <el-col :span="15">
                        <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                          placeholder="请输入value" clearable></el-input>
                      </el-col>
                      <el-col :span="2">
                        <el-button type="danger" style="margin-top: 12px" size="small" @click="removeDomain(domain)"
                          :icon="Minus" />
                      </el-col>
                    </el-row>
                  </template>
                  <div class="flex-c" style="width: 100%">
                    <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 80%" class="mt-10">
                      添加扩展
                    </el-button>
                  </div>
                </template>

                <template v-else>
                  <el-input v-model="formData[item.prop]" :placeholder="item.placeholder"></el-input>
                </template>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="content_box" v-show="stepActive == 2">
          <el-form ref="formUrl" :model="imgParams" label-width="120" :rules="rulesUrl">
            <el-form-item label="产品banner" prop="attachmentUri">
              <el-upload class="upload" :class="{ uploadImg: imgShow }" :on-change="uploadChange" action="#"
                :file-list="fileList" v-model="imgParams.attachmentUri" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :http-request="handleUpload"
                :limit="1">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>

      </div>
    </div>
    <template #footer>
      <span class="dialog-footer flex-x-c">
        <el-button v-if="stepActive == 2" @click="last"> 上一步 </el-button>
        <el-button type="primary" @click="submit" color="#467eff" v-if="stepActive == 1">
          下一步
        </el-button>
        <el-button type="primary" @click="submit" color="#467eff" v-if="stepActive == 2">
          完成
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" style="width: 100%" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed } from "vue";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import type { UploadProps } from "element-plus";
import { Minus, Plus } from "@element-plus/icons-vue";
import { upload, addProduct, uploadImg, delAttachment } from "@/api/product";
import { useColorStore } from "@/store/common";
import { useEnumStore } from "@/store/enumeration";
import { useComListData } from "@/store/list.ts"


const { listCollect } = useComListData()
const { productType } = useEnumStore()
const commonStore = useColorStore();
const { ispSelectList } = storeToRefs(commonStore);


let formStep = ref();
let formUrl = ref();
let stepActive = ref(1);
let title = ref<any>("新建");
let dialogShow = ref(false);
let isUpload = ref(false); // 记录是否上传过图片
let isEdit = ref(false);

// 记录id
let editStepId = ref("");
let editStepUrlId = ref("");
let formData = reactive<any>({
  productCategoryCode: "",
  productCode: "",
  productName: "",
  productType: "",
  schemeCode: "",
  productBannerUri: "",
  isp: "",
  isShow: "",
  productTitle: "",
  productSubTitle: "",
  isStatistics: "",
  supplierCode: "",
  supplierExtInfo: [
    {
      key: null,
      value: null,
    },
  ],
});
let imgParams = reactive<any>({
  attachmentAliasName: "",
  attachmentName: "",
  attachmentUri: "",
  attachmentType: "1",
  id: "",
  productCode: "",
});
const filterName = (val: any, name: string) => {
  if(name == 'productType' && val==1){
    formData.schemeCode=null
  }
  console.log(val, name);

}
const removeDomain = (item: any) => {
  if (formData.supplierExtInfo.length == 1) return;
  const index = formData.supplierExtInfo.indexOf(item);
  if (index !== -1) {
    formData.supplierExtInfo.splice(index, 1);
  }
};
const btnAdd = () => {
  formData.supplierExtInfo.push({
    key: null,
    value: null,
  });
};

/*配置项*/
const propsDialog = reactive({
  step1: [
    {
      type: "select",
      label: "供应商",
      placeholder: "请选择供应商",
      prop: "supplierCode",
      filterable: true,
      options: [],
    },
    {
      type: "select",
      label: "运营商",
      prop: "isp",
      placeholder: "请选择运营商",
      options: ispSelectList,
    },
    {
      type: "select",
      label: "产品大类",
      prop: "productCategoryCode",
      placeholder: "请选择产品大类",
      options: []
    },
    {
      type: "input",
      label: "产品编码",
      prop: "productCode",
      placeholder: "请输入产品编码",
    },
    {
      type: "input",
      label: "产品名称",
      prop: "productName",
      placeholder: "请输入产品名称",
    },
    {
      type: "select",
      label: "产品类型",
      prop: "productType",
      placeholder: "请选择产品类型",
      options: productType
    },
    {
      type: "select",
      label: "方案编码",
      prop: "schemeCode",
      placeholder: "请选择方案编码",
      options: []
    },
    {
      type: "select",
      label: "是否展示",
      prop: "isShow",
      placeholder: "请选择",
      options: [
        { key: 1, value: "是" },
        { key: 2, value: "否" },
      ],
    },
    {
      type: "input",
      label: "产品标题",
      prop: "productTitle",
      placeholder: "请输入产品标题",
    },
    {
      type: "input",
      label: "产品副标题",
      prop: "productSubTitle",
      placeholder: "请输入产品副标题",
    },
    {
      type: "select",
      label: "是否统计",
      prop: "isStatistics",
      placeholder: "请选择",

      options: [
        { key: 1, value: "是" },
        { key: 2, value: "否" },
      ],
    },

    {
      type: "custom",
      label: "供应商扩展信息",
      prop: "supplierExtInfo",
      placeholder: "请输入供应商扩展信息",
    },
  ],
  step2: [
    {
      type: "upload",
      label: "产品banner",
      prop: "productBannerUri",
      placeholder: "请上传banner",
    },
  ],
});
const rules = reactive<any>({});
const rulesUrl = reactive({
  attachmentUri: [{ required: true, message: "请上传banner", trigger: "blur" }],
});
/*rules*/
propsDialog.step1.forEach((item) => {
  if (item.prop !== "productSubTitle" && item.prop !== "supplierExtInfo") {
    if (item.type == "select") {
      rules[item.prop] = [
        { required: true, message: `请选择${item.label}`, trigger: "blur" },
      ];
    } else {
      rules[item.prop] = [
        { required: true, message: `请填写${item.label}`, trigger: "blur" },
      ];
    }
  }
});

/*供应商列表*/
const getSupplierList = async (arr: any[]) => {
  await nextTick();
  propsDialog.step1.filter((item) => {
    if (item.prop == "supplierCode" && item.type == "select") {
      item.options = arr;
    }
    if (item.prop == "schemeCode" && item.type == "select") {
      item.options = listCollect.equitySchemeList;
    }
    if (item.prop == "productCategoryCode" && item.type == "select") {
      item.options = listCollect.totalProduct;
    }
  });
};

/* 文件上传 */

const fileList = ref<any[]>([]);
const imgShow = computed(() => {
  return fileList.value.length > 0;
});
const uploadChange = () => { };

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = () => {
  if (editStepUrlId.value && editStepUrlId.value !== "") {
    delAttachment({ id: editStepUrlId.value }).then((res) => {
      if (res.code == 20000) {
        fileList.value = [];
        imgParams.attachmentUri = "";
        editStepUrlId.value = "";
      }
    });
  } else {
    fileList.value = [];
    imgParams.attachmentUri = "";
  }
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleUpload = (file: any) => {
  let fd = new FormData();
  fd.append("file", file.file);
  fd.append("param", JSON.stringify({ module: "product", type: "banner" }));
  upload(fd).then((res) => {
    isUpload.value = true;
    let { data } = res;
    fileList.value.push({
      name: data.attachmentName,
      url: data.attachmentUri,
    });
    imgParams.attachmentName = data.attachmentName;
    imgParams.attachmentUri = data.attachmentUri;
    imgParams.attachmentAliasName = data.attachmentAliasName;
    imgParams.productCode = formData.productCode;
    // formUrlData.attachmentUri = data.attachmentUri
    // imgShow.value= true
  });
};

const handDiglogShow = (tit?: string) => {
  dialogShow.value = !dialogShow.value;
  title.value = tit;

  // 做拦截
  nextTick(() => {
    if (tit) {
    }
  });
  // fileList.value=[]
};

const emit = defineEmits(["tableFlush"]);
const last = () => {
  isEdit.value = true;
  if (stepActive.value == 1) return;
  stepActive.value--;
};
const convertToExtInfoJson = (array: any) => {
  const newObj: any = {};
  array.forEach((item: any) => {
    if (
      item.key !== null &&
      item.value !== null &&
      item.key !== "" &&
      item.value !== ""
    ) {
      newObj[item.key] = item.value;
    }
  });
  return JSON.stringify(newObj);
};
const convertFromExtInfoJson = (extInfoJson: any) => {
  const extInfoObj = JSON.parse(extInfoJson);
  const array = [];
  for (let key in extInfoObj) {
    array.push({ key: key, value: extInfoObj[key] });
  }

  // 返回转换后的数组
  return array;
};
/*提交操作*/
const submit = async () => {
  await nextTick(() => { });
  if (stepActive.value == 1) {
    await formStep?.value.validate((valid: any) => {
      if (valid) {
        if (editStepId.value) {
          let obj = { ...formData };
          obj.supplierExtInfo = convertToExtInfoJson(formData.supplierExtInfo); // json转换
          if (editStepId.value && editStepId.value !== "") {
            obj["id"] = editStepId.value;
          }
          addProduct(obj).then((res) => {
            if (res.code == 20000) {
              // 附件上传
              stepActive.value++;
              editStepId.value = res.data;
              ElMessage.success(`${title.value}成功`);
              delete obj.id;
            }
          });
        } else {
          let obj = { ...formData };
          obj.supplierExtInfo = convertToExtInfoJson(formData.supplierExtInfo); // json转换
          addProduct(obj).then((res) => {
            if (res.code == 20000) {
              // 附件上传
              stepActive.value++;
              editStepId.value = res.data;
              ElMessage.success(`${title.value}成功`);
            }
          });
        }
      }
    });
  } else if (stepActive.value == 2) {
    await formUrl?.value.validate((valid: any) => {
      if (valid) {
        let obj = { ...imgParams };
        if (editStepUrlId.value && editStepUrlId.value !== "") {
          obj["id"] = editStepUrlId.value;
        }
        uploadImg(obj).then((res) => {
          if (res.code == 20000) {
            stepActive.value++;
            ElMessage.success(`${title.value}成功`);
            // 关闭
            stepActive.value = 1;
            getTable();
          }
        });
      }
    });
  }


};

// 对外暴露编辑处理函数
/*编辑*/
const editModal = (bol: boolean, roleData?: any) => {
  isEdit.value = true;
  editStepId.value = roleData.id;
  for (let key in roleData) {
    if (roleData.hasOwnProperty(key)) {
      if (formData.hasOwnProperty(key)) {
        // convertFromExtInfoJson
        if (key == "supplierExtInfo") {
          formData[key] = convertFromExtInfoJson(roleData[key]);
        } else {
          formData[key] = roleData[key];
        }
      }
    }
  }

  if (
    roleData.productAttachmentList &&
    roleData.productAttachmentList.length !== 0
  ) {
    let banner = roleData.productAttachmentList[0];
    editStepUrlId.value = banner.id;
    imgParams.attachmentName = banner.attachmentName;
    imgParams.attachmentUri = banner.attachmentUri;
    imgParams.attachmentAliasName = banner.attachmentAliasName;
    imgParams.productCode = banner.productCode;

    fileList.value = [
      {
        url: banner.attachmentUri,
      },
    ];
  }
};

/*置空*/
watch(
  () => dialogShow.value,
  (old) => {
    if (old == false) {
      isUpload.value = false;
      isEdit.value = false;
      editStepUrlId.value = "";
      editStepId.value = "";
      formStep.value?.resetFields();
      formUrl.value?.resetFields();
      formData.supplierExtInfo = [
        {
          key: null,
          value: null,
        },
      ];
      fileList.value = [];
      stepActive.value = 1;
      for (const key in imgParams) {
        if (key !== "attachmentType") {
          imgParams[key] = "";
        }
      }
    }
  }
);

const getTable = () => {
  dialogShow.value = false;
  emit("tableFlush");

};
const close = async () => {
  emit("tableFlush");
  formData.productCategoryCode = null
};

defineExpose({
  handDiglogShow,
  editModal,
  getSupplierList,
});
</script>

<style lang="scss" scope>
.flex-y-c {
  max-height: 680px;
  overflow: auto;
}

.el-row.is-justify-space-around {
  margin-bottom: 10px;
}

.modal {
  padding: 0 20px;
}

.step_box {
  box-sizing: border-box;
  margin-bottom: 40px;
  width: 100%;

  .el-step__title {
    font-size: 14px !important;
  }
}

.step_content {
  min-height: 400px;
  width: 80%;
  // background-color: skyblue;
}

.el-select {
  width: 100% !important;
}

.uploadImg {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
